package com.example.figurehecheng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.SelectOne;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.figurehecheng.common.context.BaseContext;
import com.example.figurehecheng.domain.dto.NewsDTO;
import com.example.figurehecheng.domain.entity.Image;
import com.example.figurehecheng.domain.entity.News;
import com.example.figurehecheng.domain.entity.Scenery;
import com.example.figurehecheng.domain.vo.NewsVO;
import com.example.figurehecheng.domain.vo.SceneryDetailVO;
import com.example.figurehecheng.domain.vo.SceneryVO;
import com.example.figurehecheng.domain.vo.UNewVO;
import com.example.figurehecheng.mapper.NewsMapper;
import com.example.figurehecheng.service.IImageService;
import com.example.figurehecheng.service.INewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * <p>
 * 新闻资讯表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-03-04
 */
@Service
@RequiredArgsConstructor
public class NewsServiceImpl extends ServiceImpl<NewsMapper, News> implements INewsService {
    @Autowired
    private  IImageService imageServiceImpl;
    @Autowired
    private  INewsService newsServiceImpl;
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public List<NewsVO> getNewsList() {
        // 1. 预加载所有图片数据（解决N+1问题）
        List<News> newsList = this.list(new LambdaQueryWrapper<News>()
                .orderByDesc(News::getCreatedAt));

        // 收集所有图片ID（处理空值和无效ID）
        List<Long> allImageIds = newsList.stream()
                .map(News::getImageId)
                .filter(StringUtils::isNotBlank)
                .flatMap(imageId -> Arrays.stream(imageId.split(",")))
                .map(String::trim)
                .filter(id -> !id.isEmpty())
                .map(id -> {
                    try {
                        return Long.parseLong(id);
                    } catch (NumberFormatException e) {
                        return null; // 过滤无效ID
                    }
                })
                .filter(Objects::nonNull)
                .collect(toList());

        // 批量查询图片数据（使用Map提升查找效率）
        Map<Long, String> imageUrlMap = imageServiceImpl.listByIds(allImageIds)
                .stream()
                .collect(Collectors.toMap(
                        Image::getId,
                        Image::getUrl,
                        (existing, replacement) -> existing));

        // 2. 转换处理
        return newsList.stream()
                .map(news -> {
                    NewsVO vo = new NewsVO();
                    BeanUtils.copyProperties(news, vo);
                    vo.setCreatedAt(news.getCreatedAt());

                    // 3. 处理图片逻辑
                    List<String> imageUrls = Arrays.stream(news.getImageId().split(","))
                            .map(String::trim)
                            .filter(id -> !id.isEmpty())
                            .map(id -> {
                                try {
                                    return Long.parseLong(id);
                                } catch (NumberFormatException e) {
                                    return null;
                                }
                            })
                            .filter(Objects::nonNull)
                            .map(imageUrlMap::get)
                            .filter(Objects::nonNull)
                            .collect(toList());
                    if (!imageUrls.isEmpty()) {
                        vo.setCoverImage(imageUrls.get(0));
                         vo.setImages(imageUrls); // 按需开启
                    }
                    return vo;
                })
                .collect(toList());
    }
//    @Override
//    public List<NewsVO> getNewsList() {
//        LambdaQueryWrapper<News> wrapper = new LambdaQueryWrapper<>();
//        wrapper.orderByDesc(News::getCreatedAt);  // 移除状态过滤，显示所有状态
//
//        return this.list(wrapper).stream()
//                .map(news -> {
//                    NewsVO vo = new NewsVO();
//                    BeanUtils.copyProperties(news, vo);
//                    // 手动处理日期转换
//                    if (news.getCreatedAt() != null) {
//                        vo.setCreatedAt(news.getCreatedAt());
//                    }
//                    String url = null;
//                    if (news.getImageId() != null) {
//                        Image image = imageServiceImpl.lambdaQuery().eq(Image::getId, news.getImageId()).one();
//                        if (image != null) {
//                            url = image.getUrl();
//                        }
//                    }
//                    vo.setUrl(url);
//                    String imageId = newsServiceImpl.lambdaQuery().eq(News::getId, news.getId()).one().getImageId();
//                    String[] imageIds = imageId.split(",");
//                    int[] numbers = new int[imageIds.length];
//                    for (int i = 0; i < imageIds.length; i++) {
//                        numbers[i] = Integer.parseInt(imageIds[i]);
//                    }
//                    List<String>imageList= new ArrayList<>();
//                    for (int number : numbers) {
//                        Image image = imageServiceImpl.lambdaQuery().eq(Image::getId, number).one();
//                        if (image != null) {
//                            imageList.add(image.getUrl());
//                        }
//                    }
//                    if (!imageList.isEmpty()){
//                        vo.setCoverImage(imageList.get(0));
//                        vo.setImages(imageList);
//                    }
//                    return vo;
//                })
//                .collect(toList());
//    }

    /**
     * 根据id获取新闻详情
     *
     * @param id
     * @return
     */
    @Override
    public NewsVO getNewsDetail(Long id) {
        // 根据id查询新闻详情
        News news = getById(id);
        if (news == null) {
            throw new RuntimeException("新闻不存在");
        }
        // 转换为VO
        NewsVO vo = new NewsVO();
        BeanUtils.copyProperties(news, vo);
        // 处理图片逻辑
        String imageId = newsServiceImpl.lambdaQuery().eq(News::getId, news.getId()).one().getImageId();
        String[] imageIds = imageId.split(",");
        int[] numbers = new int[imageIds.length];
        for (int i = 0; i < imageIds.length; i++) {
            numbers[i] = Integer.parseInt(imageIds[i]);
        }
        List<String>imageList= new ArrayList<>();
        for (int number : numbers) {
            Image image = imageServiceImpl.lambdaQuery().eq(Image::getId, number).one();
            if (image != null) {
                imageList.add(image.getUrl());
            }
        }
        if (!imageList.isEmpty()){
            vo.setImages(imageList);
        }
        return vo;
    }

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public boolean replyNews(Long id, String reply) {
//        News consultation = this.getById(id);
//        if (consultation == null) {
//            return false;
//        }
//
//        consultation.setReply(reply);
//        consultation.setStatus(1);
//        consultation.setUpdatedAt(LocalDateTime.now());
//
//        return this.updateById(consultation);
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteNews(Long id) {
        News news = this.getById(id);
        if (news == null) {
            return false;
        }
//        news.setIsDeleted(1);
        news.setUpdatedAt(LocalDateTime.now());
        Image one = imageServiceImpl.lambdaQuery().eq(Image::getId, news.getImageId()).one();
        imageServiceImpl.removeById(one);
        return removeById(id);
    }

    @Override
    public Integer create(NewsDTO dto) {
        // 1. 数据校验
        if (dto == null) {
            throw new IllegalArgumentException("NewsDTO 不能为 null");
        }
        // 2. 处理图片ID数组
        String imgidlist = "";
        if (dto.getImageIds() != null && !dto.getImageIds().isEmpty()) {
            imgidlist = dto.getImageIds().stream()
                    .map(Object::toString)
                    .collect(Collectors.joining(","));
        }
        // 3. DTO 转 Entity
        News news = new News();
        BeanUtils.copyProperties(dto, news);
    
        // 4. 设置系统字段
        LocalDateTime now = LocalDateTime.now();
        news.setCreatedAt(now);
        news.setUpdatedAt(now);
        news.setPublishTime(now);
        news.setImageId(imgidlist);
    
        // 5. 保存到数据库
        save(news);
    
        // 6. 返回新创建的新闻ID
        return news.getId();
    }

    /**
     * 根据名称搜索咨询
     * @param name
     * @return
     */
    @Override
    public List<NewsVO> searchNewsByName(String name) {
        LambdaQueryWrapper<News> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(News::getTitle, name);
        List<News> newsList = list(queryWrapper);

        return newsList.stream().map(news -> {
            NewsVO vo = new NewsVO();
            BeanUtils.copyProperties(news, vo);
            List<Image> images = imageServiceImpl.lambdaQuery()
                    .eq(Image::getId, news.getImageId())
                    .list();
            System.out.println(images);
            if (images != null && !images.isEmpty()) {
                vo.setCoverImage(images.get(0).getUrl());
            }
            return vo;
        }).collect(toList());
    }


    private NewsVO NewsDTO(News news) {
        NewsVO dto = new NewsVO();
        BeanUtils.copyProperties(news, dto);
        dto.setCreatedAt(LocalDateTime.parse(news.getCreatedAt().format(DATE_TIME_FORMATTER)));
        return dto;
    }
}
